<template>
  <div class="particle-container">
    <vue-particles id="tsparticles" :particlesInit="particlesInit" :options="particlesOptions" />
    <div class="form-box-wrapper">
      <div class="form-box" style="width: 500px; padding: 40px;">
        <div class="form-value">
          <h2>注册</h2>
          <p>加入智慧护理培训系统，开启专业成长之旅</p>
          <el-form :model="form" :rules="rules" ref="formRef" @submit.prevent="register" label-position="top"
            class="register-form">
            <el-form-item label="用户名" prop="username">
              <el-input v-model="form.username" placeholder="请输入用户名" size="large"></el-input>
            </el-form-item>
            <el-row :gutter="20">
              <el-col :span="12">
                <el-form-item label="姓" prop="firstName">
                  <el-input v-model="form.firstName" placeholder="请输入姓" size="large"></el-input>
                </el-form-item>
              </el-col>
              <el-col :span="12">
                <el-form-item label="名" prop="lastName">
                  <el-input v-model="form.lastName" placeholder="请输入名" size="large"></el-input>
                </el-form-item>
              </el-col>
            </el-row>

            <el-form-item label="电子邮箱" prop="email">
              <el-input v-model="form.email" placeholder="请输入电子邮箱" size="large"></el-input>
            </el-form-item>
            <el-row :gutter="20">
              <el-col :span="12">
                <el-form-item label="年龄" prop="age">
                  <el-input-number v-model="form.age" :min="1" :max="150" placeholder="年龄" size="large"
                    style="width: 100%;" />
                </el-form-item>
              </el-col>
              <el-col :span="12">
                <el-form-item label="手机号" prop="phone">
                  <el-input v-model="form.phone" placeholder="请输入手机号" size="large"></el-input>
                </el-form-item>
              </el-col>
            </el-row>
            <el-form-item label="注册角色" prop="role">
              <el-select v-model="form.role" placeholder="请选择注册角色" size="large" style="width: 100%;">
                <el-option label="护理学员" value="护理学员"></el-option>
                <el-option label="培训导师" value="培训导师"></el-option>
              </el-select>
            </el-form-item>
            <el-form-item label="设置密码" prop="password">
              <el-input type="password" v-model="form.password" show-password placeholder="请设置密码"
                size="large"></el-input>
            </el-form-item>
            <el-form-item label="确认密码" prop="confirmPassword">
              <el-input type="password" v-model="form.confirmPassword" show-password placeholder="请再次输入密码"
                size="large"></el-input>
            </el-form-item>
            <el-form-item prop="agreeTerms">
              <el-checkbox v-model="form.agreeTerms">
                我已阅读并同意
                <a href="#" class="text-decoration-none">服务条款</a> 和
                <a href="#" class="text-decoration-none">隐私政策</a>
              </el-checkbox>
            </el-form-item>
            <el-form-item>
              <button type="button" @click="register" class="login-btn" :disabled="isLoading">
                {{ isLoading ? "注册中..." : "注册" }}
              </button>
            </el-form-item>
          </el-form>
          <div class="register-link">
            <p>已有账号? <router-link to="/login">立即登录</router-link></p>
          </div>
        </div>
      </div>
    </div>
  </div>
</template>

<script setup>
import { ref, reactive } from "vue";
import { useRouter } from "vue-router";
import { useUserStore } from "@/stores/user.js";
import { ElMessage } from "element-plus"; // 建议引入消息提示
//import "@/assets/css/login-form.css";
import { loadSlim } from "tsparticles-slim";
const router = useRouter();
const userStore = useUserStore();
const formRef = ref(null);
const isLoading = ref(false);
const form = reactive({
  username: "", // 新增：与表单项对应
  firstName: "",
  lastName: "",
  email: "",
  age: undefined, // 新增：年龄，初始为 undefined 以便 placeholder 显示
  phone: "",
  role: "请选择注册角色",
  password: "",
  confirmPassword: "",
  agreeTerms: false,
});
const validatePass2 = (rule, value, callback) => {
  if (value === "") {
    callback(new Error("请再次输入密码"));
  } else if (value !== form.password) {
    callback(new Error("两次输入的密码不一致!"));
  } else {
    callback();
  }
};
const particlesInit = async (engine) => {
  await loadSlim(engine);
};
const rules = reactive({
  username: [{ required: true, message: "请输入用户名", trigger: "blur" }],
  firstName: [{ required: true, message: "请输入姓氏", trigger: "blur" }],
  lastName: [{ required: true, message: "请输入名字", trigger: "blur" }],
  email: [
    { required: true, message: "请输入电子邮箱", trigger: "blur" },
    {
      type: "email",
      message: "请输入有效的邮箱地址",
      trigger: ["blur", "change"],
    },
  ],
  age: [{ required: true, message: "请输入您的年龄", trigger: "blur" }],
  phone: [
    { required: true, message: "请输入您的手机号", trigger: "blur" },
    {
      pattern: /^1[3-9]\d{9}$/,
      message: "请输入有效的手机号",
      trigger: "blur",
    },
  ],
  role: [{ required: true, message: "请选择您的角色", trigger: "change" }],
  password: [
    { required: true, message: "请输入密码", trigger: "blur" },
    { min: 4, message: "密码长度至少4位", trigger: "blur" },
  ],
  confirmPassword: [
    { required: true, message: "请再次输入密码", trigger: "blur" },
    { validator: validatePass2, trigger: "blur" },
  ],
  agreeTerms: [
    {
      validator: (rule, value, callback) => {
        if (!value) {
          callback(new Error("请先阅读并同意服务条款"));
        } else {
          callback();
        }
      },
      trigger: "change",
    },
  ],
});
const register = () => {
  if (!formRef.value) return;
  formRef.value.validate((valid) => {
    if (valid) {
      isLoading.value = true;
      const roleIdMap = { 护理学员: 3, 培训导师: 2 };
      const payload = {
        username: form.username,
        password: form.password,
        age: form.age,
        name: `${form.firstName}${form.lastName}`,
        email: form.email,
        phone: form.phone,
        roleId: roleIdMap[form.role] || 3, // 默认角色为学员
        stage: "internal", // 默认阶段
      };

      // 定义成功和失败的回调函数
      const onRegisterSuccess = () => {
        // 成功时，只需要停止加载状态即可
        // 提示和跳转已在 store action 中处理
        isLoading.value = false;
      };
      console.log("即将调用的 userStore 实例:", userStore);

      const onRegisterFailure = (errorMessage) => {
        // 失败时，也只需要停止加载状态
        // 错误提示已在 store action 中处理
        console.error("注册失败，来自 store 的消息:", errorMessage);
        isLoading.value = false;
      };

      // 调用 store 的 action，并传入 payload 和两个回调函数
      userStore.register(payload, onRegisterSuccess, onRegisterFailure);
    } else {
      ElMessage.error("表单校验失败，请检查您的输入！");
      return false;
    }
  });
};
const particlesOptions = reactive({
  background: {
    color: {
      value: 'transparent'
    }
  },
  fpsLimit: 60,
  interactivity: {
    events: {
      onClick: {
        enable: true,
        mode: 'push'
      },
      onHover: {
        enable: true,
        mode: 'grab'
      },
    },
    modes: {
      push: {
        quantity: 4
      },
      grab: {
        distance: 140,
        links: {
          opacity: 1
        }
      }
    }
  },
  // particles: {
  //     color: {
  //         value: '#ffffff'
  //     },
  //     links: {
  //         color: '#ffffff',
  //         distance: 150,
  //         enable: true,
  //         opacity: 0.4,
  //         width: 1
  //     },
  //     move: {
  //         direction: 'none',
  //         enable: true,
  //         outModes: {
  //             default: 'out'
  //         },
  //         random: false,
  //         speed: 2,
  //         straight: false
  //     },
  //     number: {
  //         density: {
  //             enable: true,
  //         },
  //         value: 80
  //     },
  //     opacity: {
  //         value: 0.5
  //     },
  //     shape: {
  //         type: 'circle'
  //     },
  //     size: {
  //         value: { min: 1, max: 3 }
  //     }
  // },
  particles: {
    color: {
      value: '#ffffff'
    },
    links: {
      color: '#ffffff',
      distance: 150,
      enable: true,
      opacity: 0.25, // 降低连接线透明度，让粒子形状更突出
      width: 1
    },
    move: {
      direction: 'none',
      enable: true,
      outModes: {
        default: 'out'
      },
      random: true, // 改为随机移动，更有活力
      speed: 1.5,   // 稍微加快速度
      straight: false
    },
    number: {
      density: {
        enable: true,
      },
      value: 100 // 增加粒子数量，使其更密集
    },
    opacity: {
      value: { min: 0.4, max: 0.8 } // 透明度随机，增加层次感
    },
    shape: {
      type: ['triangle', 'char'], // 关键：类型设置为数组，包含三角形和字符
      character: {
        value: ['+', '✚'], // 使用加号字符作为粒子
        font: 'Verdana',
        style: '',
        weight: '800'
      }
    },
    size: {
      value: { min: 4, max: 10 } // 增大粒子的尺寸范围
    }
  },
  detectRetina: true
});
</script>

<style scoped>
/* 新增：定义淡入动画 */
@keyframes fadeInUp {
  from {
    opacity: 0;
    transform: translateY(20px);
  }

  to {
    opacity: 1;
    transform: translateY(0);
  }
}

.particle-container {
  position: relative;
  width: 100vw;
  height: 100vh;
  background: linear-gradient(to bottom right, #87CEEB, #B0E0E6);
  overflow: auto;
  display: flex;
  justify-content: center;
  align-items: center;
  padding: 20px;
}

#tsparticles {
  position: absolute;
  top: 0;
  left: 0;
  width: 100%;
  height: 100%;
  z-index: 1;
}

.form-box-wrapper {
  position: relative;
  z-index: 2;
  margin: auto;
  /* 新增：应用动画 */
  animation: fadeInUp 0.8s ease-out forwards;
}

.form-box {
  position: relative;
  width: 500px;
  background: rgba(44, 62, 80, 0.85);
  border: 1px solid rgba(255, 255, 255, 0.1);
  border-radius: 15px;
  backdrop-filter: blur(8px);
  padding: 40px;
  transition: all 0.3s ease;
  color: #fff;
}

/* ...后续样式与您之前确认的版本保持一致... */

.register-form :deep(.el-form-item__label) {
  color: #fff !important;
  padding-bottom: 2px;
}

.register-form :deep(.el-input__wrapper),
.register-form :deep(.el-select__wrapper),
.register-form :deep(.el-input-number) {
  background-color: transparent !important;
  box-shadow: none !important;
  border-bottom: 2px solid #fff;
  border-radius: 0;
}

.register-form :deep(.el-input__inner),
.register-form :deep(.el-select__input) {
  color: #fff !important;
  height: 40px;
}

.register-form :deep(input::placeholder) {
  color: rgba(255, 255, 255, 0.7) !important;
}

.register-form :deep(.el-checkbox__label) {
  color: #fff;
}

.register-form :deep(.el-checkbox__input.is-checked .el-checkbox__inner) {
  background-color: #fff;
  border-color: #fff;
}

.register-form :deep(.el-checkbox__inner::after) {
  border-color: #4e73df;
}

.login-btn {
  width: 100%;
  height: 40px;
  border-radius: 40px;
  background: #fff;
  border: none;
  outline: none;
  cursor: pointer;
  font-size: 1em;
  font-weight: 600;
  color: #4e73df;
}

.register-link {
  font-size: .9em;
  color: #fff;
  text-align: center;
  margin-top: 25px;
}

.register-link p a {
  text-decoration: none;
  color: #fff;
  font-weight: 600;
}

.register-link p a:hover {
  text-decoration: underline;
}

:deep(.el-select-dropdown) {
  background: rgba(44, 62, 80, 0.85) !important;
  border: 1px solid rgba(255, 255, 255, 0.2) !important;
  backdrop-filter: blur(10px);
}

:deep(.el-select-dropdown__item) {
  color: #fff !important;
}

:deep(.el-select-dropdown__item.hover),
:deep(.el-select-dropdown__item:hover) {
  background-color: rgba(255, 255, 255, 0.1) !important;
}

:deep(.el-select-dropdown__item.is-selected) {
  background-color: rgba(78, 115, 223, 0.5) !important;
  color: #fff !important;
  font-weight: bold;
}

:deep(.el-popper__arrow::before) {
  background: transparent !important;
  border: none !important;
}
</style>

<!-- <template>
  <div class="auth-container">
    <div class="auth-card">
      <div class="auth-form-panel">
        <div class="form-content">
          <div class="logo-header">
            <h2>注册新账号</h2>
          </div>
          
          <el-form
            :model="form"
            :rules="rules"
            ref="formRef"
            @submit.prevent="register"
            label-position="top"
            class="auth-el-form mt-4"
          >
             <el-form-item prop="username">
                <el-input v-model="form.username" placeholder="设置用户名" size="large" :prefix-icon="User" />
              </el-form-item>
              
              <el-row :gutter="10">
                <el-col :span="12">
                  <el-form-item prop="firstName">
                    <el-input v-model="form.firstName" placeholder="姓" size="large"></el-input>
                  </el-form-item>
                </el-col>
                <el-col :span="12">
                  <el-form-item prop="lastName">
                    <el-input v-model="form.lastName" placeholder="名" size="large"></el-input>
                  </el-form-item>
                </el-col>
              </el-row>
              
              <el-form-item prop="email">
                <el-input v-model="form.email" placeholder="电子邮箱" size="large" :prefix-icon="Message" />
              </el-form-item>

              <el-form-item prop="password">
                <el-input type="password" v-model="form.password" show-password placeholder="设置密码" size="large" :prefix-icon="Lock" />
              </el-form-item>

              <el-form-item prop="confirmPassword">
                <el-input type="password" v-model="form.confirmPassword" show-password placeholder="确认密码" size="large" :prefix-icon="CircleCheck" />
              </el-form-item>
              
              <el-form-item prop="agreeTerms" class="agree-terms">
                <el-checkbox v-model="form.agreeTerms">
                  我已阅读并同意<a href="#">服务条款</a>
                </el-checkbox>
              </el-form-item>

              <el-form-item>
                <button type="button" @click="register" class="auth-btn" :disabled="isLoading">
                  {{ isLoading ? "注册中..." : "立即注册" }}
                </button>
              </el-form-item>
          </el-form>

          <div class="switch-link">
            <p>已有账号? <router-link to="/login">立即登录</router-link></p>
          </div>
        </div>
      </div>
      
      <div class="auth-info-panel">
        <img src="/images/auth-illustrationSmall.png" alt="Illustration" />
      </div>
    </div>
  </div>
</template>

<script setup>
import { ref, reactive } from "vue";
import { useRouter } from "vue-router";
import { useUserStore } from "@/stores/user.js";
import { ElMessage } from "element-plus";
import "@/assets/css/login-form.css";
import { User, Lock, Message, CircleCheck } from '@element-plus/icons-vue';
const router = useRouter();
const userStore = useUserStore();
const formRef = ref(null);
const isLoading = ref(false);

const form = reactive({
  username: "",
  firstName: "",
  lastName: "",
  email: "",
  age: undefined,
  phone: "",
  role: "",
  password: "",
  confirmPassword: "",
  agreeTerms: false,
});

const validatePass2 = (rule, value, callback) => {
  if (value === "") {
    callback(new Error("请再次输入密码"));
  } else if (value !== form.password) {
    callback(new Error("两次输入的密码不一致!"));
  } else {
    callback();
  }
};

const rules = reactive({
  username: [{ required: true, message: "请输入用户名", trigger: "blur" }],
  firstName: [{ required: true, message: "请输入姓氏", trigger: "blur" }],
  lastName: [{ required: true, message: "请输入名字", trigger: "blur" }],
  email: [
    { required: true, message: "请输入电子邮箱", trigger: "blur" },
    { type: "email", message: "请输入有效的邮箱地址", trigger: ["blur", "change"] },
  ],
  role: [{ required: true, message: '请选择您的角色', trigger: 'change' }],
  password: [
    { required: true, message: "请输入密码", trigger: "blur" },
    { min: 4, message: "密码长度至少4位", trigger: "blur" },
  ],
  confirmPassword: [
    { required: true, message: "请再次输入密码", trigger: "blur" },
    { validator: validatePass2, trigger: "blur" },
  ],
  agreeTerms: [
    {
      validator: (rule, value, callback) => {
        if (!value) {
          callback(new Error("请先阅读并同意服务条款"));
        } else {
          callback();
        }
      },
      trigger: "change",
    },
  ],
});

const register = () => {
  if (!formRef.value) return;
  formRef.value.validate((valid) => {
    if (valid) {
      isLoading.value = true;
      const roleIdMap = { "护理学员": 3, "培训导师": 2 };
      const payload = {
        username: form.username,
        password: form.password,
        age: form.age,
        name: `${form.firstName}${form.lastName}`,
        email: form.email,
        phone: form.phone,
        roleId: roleIdMap[form.role] || 3,
        stage: form.role === '护理学员' ? "intern" : "formal"
      };
      
      const onRegisterSuccess = () => {
        isLoading.value = false;
      };
      
      const onRegisterFailure = (errorMessage) => {
        console.error("注册失败，来自 store 的消息:", errorMessage);
        isLoading.value = false;
      };

      userStore.register(payload, onRegisterSuccess, onRegisterFailure);
    } else {
      ElMessage.error("表单校验失败，请检查您的输入！");
      return false;
    }
  });
};
</script>

<style scoped>
@import "@/assets/css/login-form.css";
</style> -->